package com.wanmait.zaisousuo.filter;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.wanmait.zaisousuo.service.CityService;
import com.wanmait.zaisousuo.service.UserinfoService;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.util.EntityUtils;
import org.springframework.stereotype.Service;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;

import javax.annotation.Resource;
import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;
import java.nio.charset.StandardCharsets;

@WebFilter(filterName = "getCityFilter",value ={"/web/*","/"})
public class getCityFilter implements Filter {


    private CityService cityService;

    public void destroy() {
    }
    public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws ServletException, IOException {
        HttpServletRequest request1 = (HttpServletRequest) req;
        HttpSession session = request1.getSession();
        Object city = session.getAttribute("city");
        if (city == null) {
            String ip = java.net.InetAddress.getLocalHost().getHostAddress();
//            ip="123.125.114.144";
            String url ="http://api.map.baidu.com/location/ip?ip="+ip+"&ak=kgQ84GVFUVqvYZStZetGqtc3jQsf1crG"; ;
            URLConnection urlConnection = null;
            try {
                urlConnection = new URL(url).openConnection();
                urlConnection.connect();//打开与服务器的连接
                StringBuilder stringBuilder = new StringBuilder();
                //读取服务器的响应
                BufferedReader reader  = new BufferedReader(new InputStreamReader(urlConnection.getInputStream(), StandardCharsets.UTF_8));
                String line = null;
                while((line = reader.readLine()) != null){
                    stringBuilder.append(line);
                }
                //把数据解析为JSON
                JSONObject ipInfo = JSON.parseObject(stringBuilder.toString());
                if(ipInfo.getJSONObject("content")==null)
                {
                    session.setAttribute("city","青岛市");
                    Integer cityId=cityService.findByName("青岛市",false).getId();
                    session.setAttribute("cityId",cityId);
                    session.setAttribute("province","山东省");
                    Integer provinceId=cityService.findByName("山东省",true).getId();
                    session.setAttribute("provinceId",provinceId);
                    chain.doFilter(req, resp);
                    return;
                }
                String cityx=ipInfo.getJSONObject("content").getJSONObject("address_detail").getString("city");
                session.setAttribute("city",cityx);
                session.setAttribute("cityId",cityService.findByName(cityx,true).getId());
                String provincex=ipInfo.getJSONObject("content").getJSONObject("address_detail").getString("province");
                session.setAttribute("province",provincex);
                session.setAttribute("province",cityService.findByName(provincex,false).getId());
//              session.setAttribute("cityId",ipInfo.getJSONObject("data").getString("city_id"));
                chain.doFilter(req, resp);
            } catch (IOException e) {
                e.printStackTrace();
            }
        } else {
            chain.doFilter(req, resp);
        }

    }

    public void init(FilterConfig config) throws ServletException {

        ServletContext sc = config.getServletContext();
        WebApplicationContext cxt = WebApplicationContextUtils.getWebApplicationContext(sc);
        if(cxt != null && cxt.getBean(CityService.class)!= null && cityService == null)
            cityService = cxt.getBean(CityService.class);
    }

}
